package com.example.callcenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.callcenter.dto.LoginDTO;
import com.example.callcenter.dto.TokenDTO;
import com.example.callcenter.entity.SysUser;
import com.example.callcenter.mapper.SysUserMapper;
import com.example.callcenter.service.AuthService;
import com.example.callcenter.util.JwtUtils;
import com.example.callcenter.util.PasswordUtil;
import com.example.callcenter.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;  // 注入Jwt工具类

    @Override
    public ResultUtil login(LoginDTO loginDTO) {
        // 1. 查询用户
        SysUser user = userMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("username", loginDTO.getUsername()));
        if (user == null) {
            return ResultUtil.error("用户名不存在");
        }

        // 2. 验证密码
        if (!PasswordUtil.verify(loginDTO.getPassword(), user.getPassword())) {
            return ResultUtil.error("密码错误");
        }

        // 3. 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateById(user);

        // 4. 生成令牌
        String accessToken = jwtUtils.generateAccessToken(user.getId(), user.getUsername(), user.getRole());
        String refreshToken = jwtUtils.generateRefreshToken(user.getId());

        // 5. 构建返回的TokenDTO
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setAccessToken(accessToken);
        tokenDTO.setRefreshToken(refreshToken);
        // 关键修改：动态获取过期时间（从JwtUtils获取，与配置一致）
        tokenDTO.setExpire((int) jwtUtils.getAccessTokenExpireMinutes());
        tokenDTO.setTokenType("Bearer");

        return ResultUtil.success(tokenDTO);
    }

    @Override
    public ResultUtil refreshToken(String refreshToken) {
        try {
            // 1. 从refreshToken中解析用户ID
            Long userId = jwtUtils.getUserId(refreshToken);
            // 2. 查询用户信息
            SysUser user = userMapper.selectById(userId);
            // 3. 生成新的accessToken
            String newAccessToken = jwtUtils.generateAccessToken(user.getId(), user.getUsername(), user.getRole());

            // 4. 构建返回的TokenDTO
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setAccessToken(newAccessToken);
            // 关键修改：动态获取过期时间（与登录时一致）
            tokenDTO.setExpire((int) jwtUtils.getAccessTokenExpireMinutes());
            tokenDTO.setTokenType("Bearer");
            return ResultUtil.success(tokenDTO);
        } catch (Exception e) {
            return ResultUtil.error("刷新Token失败");
        }
    }
}